//
//  ICMessageForwardController.m
//  ICome
//
//  Created by ENN on 16/7/15.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMessageForwardController.h"
#import "ICChatForwardCell.h"
#import "ICMessageModel.h"
#import "ICGroup.h"
#import "LCBLayoutButton.h"
#import "ICSearchButton.h"
#import "ICMessageForwardSearchController.h"
//重构提取
#import "ICReceiveShareObject.h"
#import "ICSendMessageHelper.h"
#import "ICOrganizationViewController.h"
#import "NSData+Image.h"
#import "ICFileTool.h"
#define layoutButtonHeight 34

@interface ICMessageForwardController ()<UITableViewDelegate,UITableViewDataSource,ICForwardSearchDelegate>

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray * selectedArr;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UIView *tableHearView;
@property (nonatomic, strong) UIScrollView * hearScrollView;
@property (nonatomic, strong)NSMutableArray *recordgIdList;

@end

@implementation ICMessageForwardController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
    
    if (self.shareContent) { // 兼容轻应用中的分享 支持字典
        ICReceiveShareObject *shareObject = [[ICReceiveShareObject alloc] initWithDict:_shareContent[@"shareObject"]];
        [self shareContentToServer:shareObject];
    }
    if (self.shareObject) { // 支持对象
        [self shareContentToServer:self.shareObject];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setupNav];
}

- (void)shareContentToServer:(ICReceiveShareObject *)shareObject
{
    switch (shareObject.mediaType) {
        case ICMediaType_Text: {
            WEAKSELF
            ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeText
                                                                   content:shareObject.message.title
                                                                      path:nil
                                                                      from:[ICUser currentUser].eId
                                                                        to:nil
                                                                       lnk:nil
                                                                   fileKey:nil
                                                                  isSender:YES
                                                  receivedSenderByYourself:NO];
            weakSelf.messageModelsArray = @[messageF];
            break;
        }
        case ICMediaType_Image: {
            [MBProgressHUD showMessage:@"数据处理中..." toView:self.view];
            WEAKSELF
            UIImage *image = shareObject.imageObject.image;
            NSData *imageData = [NSData imageData:image];
            NSString *orgPath = [[ICMediaManager sharedManager] imagePathWithName:[NSString stringWithFormat:@"%@.png",[NSString currentName]]];
            BOOL result = [imageData writeToFile:orgPath atomically:NO];
            if (!result) NSLog(@"write share image failured");
            [[ICNetworkManager sharedInstance] sendImage:imageData imgName:[NSString stringWithFormat:@"IMG_%ld", [ICMessageHelper currentMessageTime]] progress:nil success:^(id object) {
                NSString *fileKey = [object objectForKey:@"data"];
             
                NSDictionary * dic = @{@"w":[NSString stringWithFormat:@"%.0f",image.size.width],
                                       @"h":[NSString stringWithFormat:@"%.0f",image.size.height]};
                NSString *lnk = [dic jsonString];
                NSString *content = @"[图片]";
                
                ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePic
                                                                       content:shareObject.message.title
                                                                          path:@"imgPath"
                                                                          from:[ICUser currentUser].eId
                                                                            to:@""
                                                                           lnk:lnk
                                                                       fileKey:nil
                                                                      isSender:YES
                                                      receivedSenderByYourself:NO];
                messageF.model.message.fileKey = fileKey;
                messageF.model.message.messageId = [ICMessageHelper localMessageId:content];;
                messageF.model.message.localMsgId = messageF.model.message.messageId;
                messageF.model.message.date = [ICMessageHelper currentMessageTime];
                messageF.model.message.reSend = 1; // 直接写成重发
                messageF.model.message.isAnimation = NO; // 关闭刷新
                
                weakSelf.messageModelsArray = @[messageF];
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"share image send failured:%@",error);
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [MBProgressHUD showError:@"请求失败，请稍后再试"];
            }];
            break;
        }
        case ICMediaType_Video: {
            [MBProgressHUD showError:@"暂不支持该类型"];
            break;
        }
        case ICMediaType_File: {
            // 本地是否存在文件 不存在则存储 存储文件
//            NSString *fileKey = shareObject.fileObject.fileKey;
//            NSString *extType = shareObject.fileObject.fileType;
//            NSString *fileName = [NSString stringWithFormat:@"%@.%@", shareObject.fileObject.fileName,shareObject.fileObject.fileType];
//            NSString *path = [ICFileTool filePathWithName:fileKey orgName:[fileName stringByDeletingPathExtension] type:extType];
//
//            if (![ICFileTool fileExistsAtPath:path]) {
//                [shareObject.fileObject.file writeToFile:path atomically:NO];
//            }
//            [self sendFileMessageWithFileName:[path lastPathComponent]];
            [MBProgressHUD showError:@"暂不支持该类型"];
            break;
        }
        case ICMediaType_PicURL:
        {
            [MBProgressHUD showMessage:@"数据处理中..." toView:self.view];
            WEAKSELF
            [[ICNetworkManager sharedInstance] sendImage:shareObject.message.thumbData imgName:[NSString stringWithFormat:@"IMG_%ld", [ICMessageHelper currentMessageTime]] progress:nil success:^(id object) {
                NSString *fileKey = [object objectForKey:@"data"];
                NSDictionary *key = @{
                                      @"filekey":fileKey,
                                      @"summary":shareObject.message.desc,
                                      @"source":shareObject.message.displayName
                                      };
                
                ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePicText
                                                                       content:shareObject.message.title
                                                                          path:nil
                                                                          from:[ICUser currentUser].eId
                                                                            to:@""
                                                                           lnk:shareObject.webPageObject.webpageUrl
                                                                       fileKey:nil
                                                                      isSender:YES
                                                      receivedSenderByYourself:NO];
                messageF.model.message.lnk = shareObject.webPageObject.webpageUrl;
                messageF.model.message.fileKey = [key jsonString];
                messageF.model.message.messageId = [ICMessageHelper localMessageId:@"[链接]"];
                messageF.model.message.localMsgId = messageF.model.message.messageId;
                messageF.model.message.date = [ICMessageHelper currentMessageTime];
                messageF.model.message.reSend = 1; // 直接写成重发
                messageF.model.message.isAnimation = NO; // 关闭刷新
                
                weakSelf.messageModelsArray = @[messageF];
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"share image send failured:%@",error);
                
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [MBProgressHUD showError:@"请求失败，请稍后再试"];
            }];
            break;
        }
        default:
            break;
    }
}

// 发送转发通知
- (void)postForwardNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectionForwardSelected" object:nil];
}

- (void)setupNav
{
    if (self.name) {
        self.title = self.name;
    } else {
        self.title = @"转发至";
    }
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"关闭" itemType:UIBarButtonItemTypeLeft target:self action:@selector(cancelForwardMessage)];
    
    if (self.hearScrollView.hidden) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
    } else {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"确定" itemType:UIBarButtonItemTypeRight target:self action:@selector(rightBtnClick)];
    }
}

- (void)setupUI
{
    self.tableView.frame = CGRectMake(0, 0, self.view.width, self.view.height-self.navigationController.navigationBar.height-[[UIApplication sharedApplication] statusBarFrame].size.height);
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)loadData
{
    ICGroup *group   = [[ICGroup alloc] init];
    group.gId        = @"1";
    group.gName      = @"新奥";
    group.photoId     = @"icon_organization";
    
    WEAKSELF
    //    [ICMessageDatabase getNormalGroups:^(NSArray *array, NSError *error) {
    //        weakSelf.dataArr = (NSMutableArray *)array;
    //        if(weakSelf.dataArr.count > 0){
    //            [weakSelf.dataArr insertObject:group atIndex:0];
    //        }else{
    //            [weakSelf.dataArr addObject:group];
    //        }
    //        [weakSelf.tableView reloadData];
    //    }];
    
    [self.dataArr addObject:group];
    
    // 获取自己
    [ICMessageDatabase getGroupsWithgType:ICGroup_SELF Finish:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            ICGroup *group = [[ICGroup alloc] init];
            group.gName = @"我";
            group.gId = [ICUser currentUser].eId;
            group.photoId = [ICUser currentUser].photoId;
            [weakSelf.dataArr addObject:group];
        }
        [weakSelf.tableView reloadData];
    }];
    
    // 获取最近联系人
    [ICMessageDatabase recentContactUsers:^(NSArray *array, NSError *error) {
        for(ICUser *model in array)
        {
            ICGroup *group = [[ICGroup alloc] init];
            group.gName = model.eName;
            group.gId = model.eId;
            group.photoId = model.photoId;
            [weakSelf.dataArr addObject:group];
        }
        [weakSelf.tableView reloadData];
    }];
    
    // 获取多人组
    [ICMessageDatabase getGroupsWithgType:ICGroup_MULTI Finish:^(NSArray *array, NSError *error) {
        [weakSelf.dataArr addObjectsFromArray:array];
        [weakSelf.tableView reloadData];
    }];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICChatForwardCell *cell = [ICChatForwardCell cellWithTableView:tableView];
    if(indexPath.row >0){
        cell.buttonBool = YES;
    }else if(indexPath.row == 0)
    {
        cell.buttonBool = NO;
    }
    
    //    if([self.selectedArr containsObject:self.dataArr[indexPath.row]])
    //    {
    //        cell.selectedBool = YES;
    //    }else{
    //        cell.selectedBool = NO;
    //    }
    
    ICGroup *group = self.dataArr[indexPath.row];
    NSMutableArray *gIdList = [[NSMutableArray alloc] init];
    for (ICGroup *group in self.selectedArr) {
        [gIdList addObject:group.gId];
    };
    
    if ([gIdList containsObject:group.gId]) {
        cell.selectedBool = YES;
    } else {
        cell.selectedBool = NO;
    }
    
    cell.group = group;
    WEAKSELF
    cell.chatForwardCellBlock = ^(UIButton *but,ICGroup *groupdata) {
        [weakSelf frowardBtnAction:but group:groupdata];
    };
    return cell;
}

- (void)frowardBtnAction:(UIButton *)but group:(ICGroup *)group {
    if(self.selectedArr.count == 9 && !but.isSelected){
        [MBProgressHUD showError:@"最多只能选择9个聊天"];
    }else{
        [but setSelected:!but.isSelected];
        if (but.isSelected) {
            //selected
            [but setImage:[UIImage imageNamedFromiComeSDKBundle:[NSString stringWithFormat:@"icon_video_checked"]] forState:UIControlStateSelected];
            [self.selectedArr addObject:group];
        }else{
            //normal
            [but setImage:[UIImage imageNamedFromiComeSDKBundle:[NSString stringWithFormat:@"icon_video_unchecked"]] forState:UIControlStateNormal];
            
            for (ICGroup *grp in self.selectedArr) {
                if ([grp.gId isEqualToString:group.gId]) {
                    [self.selectedArr removeObject:grp];
                    break;
                }
            }
        }
        [self.tableView reloadData];
    }
    NSLog(@"self.selectedArr.count = %ld",self.selectedArr.count);
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        [self.hearScrollView removeAllSubviews];
        if(self.selectedArr.count > 0){
            self.hearScrollView.hidden = NO;
            for (NSInteger i = 0; i < self.selectedArr.count;i++) {
                ICGroup * groupdata  =  self.selectedArr[i];
                LCBLayoutButton * button = [[LCBLayoutButton alloc] initWithFrame:CGRectMake(10+i*(layoutButtonHeight +10),(self.hearScrollView.height-layoutButtonHeight)/2.0,layoutButtonHeight, layoutButtonHeight)];
                button.imageSize = CGSizeMake(layoutButtonHeight, layoutButtonHeight);
                button.lcbRelayoutType = LCBRelayoutButtonTypeNo;
                NSURL *imgURL = [NSURL URLWithString:[ICTools getMinImageURL:(groupdata.photoId)]];
                [button sd_setImageWithURL:imgURL forState:UIControlStateNormal placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"App_personal_headimg"]];
                [button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [self.hearScrollView addSubview:button];
                self.hearScrollView.contentSize =  CGSizeMake(self.selectedArr.count*(layoutButtonHeight +10), 0);
            }
            [self setupNav];
            return 86;
        }else{
            self.hearScrollView.hidden = YES;
            [self setupNav];
        }
        return 44;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.tableHearView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.0f * Level;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        [self openOrgGroup];
    }else if(indexPath.row > 0){
        ICGroup *group = self.dataArr[indexPath.row];
        ICChatForwardCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [self frowardBtnAction:cell.rightbutton group:group];
    }
}

- (void)openOrgGroup {
    ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
    vc.singleSelect = NO;
    vc.canCancelSelect = YES;
    vc.eId = [ICUser currentUser].eId;
    vc.CtrStyle = CtrStyleSelectEmploye_sdk;
    vc.kkGroupType = GroupStyleSelectEmployee;
    vc.maxCount = 9 - self.selectedArr.count;
    WEAKSELF
    vc.selectionUserList = ^(NSArray *list) {
        
        NSMutableArray *gIdList = [[NSMutableArray alloc] init];
        for (ICGroup *group in weakSelf.selectedArr) {
            [gIdList addObject:group.gId];
        };
        
        for(ICEmpInfoModel *model in list)
        {
            ICGroup *group = [[ICGroup alloc] init];
            group.gName = model.eName;
            group.gId = model.eId;
            group.photoId = model.photoId;
            
            if (![gIdList containsObject:group.gId]) {
                [weakSelf.selectedArr addObject:group];
            }
        }
        [weakSelf.tableView reloadData];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)sendMessages:(NSString *)gId models:(NSArray *)array  {
    
    [self.recordgIdList addObject:gId];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ICMessageFrame *messageFrame = (ICMessageFrame *)obj;
        ICMessageModel *messageModel = messageFrame.model;
        ICMessage *message = [ICMessageHelper createSendMessageF:messageFrame
                                                         Message:messageModel.message.type
                                                         content:messageModel.message.content
                                                         fileKey:messageModel.message.fileKey
                                                            from:[ICUser currentUser].eId
                                                              to:gId
                                                             lnk:messageModel.message.lnk
                                                          status:nil];
        message.localMsgId = [ICMessageHelper localMessageId:message.content];
        message.messageId = message.localMsgId;
        message.date = [ICMessageHelper currentMessageTime];
        message.deliveryState = ICMessageDeliveryState_Delivering;
        
        [self saveMessage:messageModel messageId:message.messageId gId:gId];
        WEAKSELF
        [ICSendMessageHelper sendMessageWithObject:[ICMessageHelper createSendParamWithMessage:message]
                                        identifier:message.localMsgId
                                           Success:^(id object, id other) {
                                               
                                               if ([weakSelf.delegate respondsToSelector:@selector(frowardSendMessageSuccessgId:)]) {
                                                   [weakSelf.delegate frowardSendMessageSuccessgId:gId];
                                               }
                                               NSLog(@" --- 成功");
                                               [self postForwardNotification];
                                           } Failure:^(NSError *error, id other) {
                                               NSLog(@" --- 失败");
                                               
                                               if ([weakSelf.delegate respondsToSelector:@selector(frowardSendMessageSuccessgId:)]) {
                                                   [weakSelf.delegate frowardSendMessageSuccessgId:gId];
                                               }
                                               [self postForwardNotification];
                                           }];
    }];
}

- (void)saveMessage:(ICMessageModel *)messageModel
          messageId:(NSString *)messageId
                gId:(NSString *)gId {
    messageModel.message.deliveryState = ICMessageDeliveryState_Delivering;
    messageModel.message.to = gId;
    messageModel.isSender = YES;
    messageModel.message.from  = [ICUser currentUser].eId;
    messageModel.message.status = ICMessageStatus_read;
    // 失败之后，给一个本地的消息Id，重发的时候还需要更改
    messageModel.message.messageId = messageId;
    // 失败后的时间是本地时间
    NSInteger currentDate = [ICMessageHelper currentMessageTime];
    messageModel.message.date = currentDate;
    [ICMessageDatabase saveMessage:messageModel];
}

- (void)messageSendSucceed:(ICMessageModel *)messageModel
                      data:(NSDictionary *)data
{
    NSString *gId      = [data objectForKey:@"gId"];
    NSString *mId      = [data objectForKey:@"id"];
    NSInteger date     = [[data objectForKey:@"st"] integerValue];
    messageModel.message.deliveryState = ICMessageDeliveryState_Delivered;
    messageModel.message.messageId = mId;
    messageModel.message.to        = gId;
    messageModel.message.date      = date;
    messageModel.isSender          = YES;
    messageModel.message.from      = [ICUser currentUser].eId;
    messageModel.message.status    = ICMessageStatus_read;
    [ICMessageDatabase saveMessage:messageModel];
}


- (void)messageSendFailued:(ICMessageModel *)messageModel
                       gId:(NSString *)gId
{
    messageModel.message.deliveryState = ICMessageDeliveryState_Failure;
    messageModel.message.to = gId;
    messageModel.isSender   = YES;
    messageModel.message.from  = [ICUser currentUser].eId;
    messageModel.message.status    = ICMessageStatus_read;
    NSString *failMesssageId = [ICMessageHelper localMessageId:messageModel.message.content];
    // 失败之后，给一个本地的消息Id，重发的时候还需要更改
    messageModel.message.messageId = failMesssageId;
    // 失败后的时间是本地时间
    NSInteger currentDate = [ICMessageHelper currentMessageTime];
    messageModel.message.date      = currentDate;
    [ICMessageDatabase saveMessage:messageModel];
}

-(void)BtnClick:(LCBLayoutButton * )but
{
    ICGroup * group = (ICGroup *)but.lcbButtondata;
    [self.selectedArr removeObject:group];
    [self.tableView reloadData];
}

#pragma mark - searchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ICSEARCHCANCELCOLOR forState:UIControlStateNormal];
        }
    }
}

#pragma mark - ICForwardSearchDelegate

- (void)groupSearch:(ICGroup *)group
{
    if(self.selectedArr.count == 9){
        [MBProgressHUD showSuccess:@"最多只能选择9个聊天"];
    } else {
        NSMutableArray *gIdList = [[NSMutableArray alloc] init];
        for (ICGroup *group in self.selectedArr) {
            [gIdList addObject:group.gId];
        };
        
        if (![gIdList containsObject:group.gId]) {
            [self.selectedArr addObject:group];
            [self.tableView reloadData];
        }
    }
}


#pragma mark - Event

- (void)cancelForwardMessage
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)rightBtnClick {
    NSMutableArray *list = [[NSMutableArray alloc] init];
    for (ICGroup *group in self.selectedArr) {
        [list addObject:group.gName];
    }
    NSString *title = [list componentsJoinedByString:@"、"];
    UIAlertController *alertCtr = [UIAlertController alertControllerWithTitle:@"确定发送给:" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel   = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sendShareMessages];
    }];
    [alertCtr addAction:cancel];
    [alertCtr addAction:okAction];
    [self presentViewController:alertCtr animated:YES completion:nil];
}

- (void)sendShareMessages {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    [MBProgressHUD showMessage:@"消息发送中..." toView:self.view];
    WEAKSELF
    __block int index = 0;
    for (int i = 0; i < self.selectedArr.count; i++) {
        
        ICGroup *grp = [self.selectedArr objectAtIndex:i];
        NSString *gId = grp.gId; // 存在无关系的人员，gId 可能是eId 走else方法
        dispatch_group_async(group, queue, ^{
            if ([gId hasPrefix:@"slf_"] || // 自己
                [gId hasPrefix:@"dbl_"] || // 双人
                [gId hasPrefix:@"mlt_"] || // 多人
                [gId hasPrefix:@"rbt_"] ) {// 客服
                [weakSelf sendMessages:gId models:weakSelf.messageModelsArray]; // 消息发送
                index++;
                if (index == weakSelf.selectedArr.count) {
                    // 结束
                    [weakSelf updateStatus];
                }
            } else {
                // 单人 优化操作是本地查找该群组
                NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                                        @"eName":[ICUser currentUser].eName,
                                        @"otherId":gId};
                [ICCreateGroupManager createTwoGroupWith:param Handle:^(ICGroup *group) {
                    // 组id
                    if (group) {
                        [weakSelf sendMessages:group.gId models:weakSelf.messageModelsArray]; // 消息发送
                    }
                    
                    index++;
                    if (index == weakSelf.selectedArr.count) {
                        // 结束
                        [weakSelf updateStatus];
                    }
                }];
            }
        });
    }
}

- (void)updateStatus
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [ICNotification postNotificationName:NotificationUpdateGroupList object:nil userInfo:nil];
        WEAKSELF
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            for (NSString *gId in weakSelf.recordgIdList) {
                int unreadCount = [ICMessageDatabase getGroupUnreadMessageCountWithGroupId:gId];
                if (unreadCount == 1) {
                    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:gId count:0]; // 清除未读数
                    [ICMessageDatabase updateGroupAlertStatus:0 gId:gId];
                    [ICMessageHelper updateGroupReadWithGroupId:gId];
                }
            }
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showSuccess:@"发送成功"];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            
        });
    });
}

#pragma mark - Getter

- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
    }
    return _tableView;
}

-(UIView *)tableHearView
{
    if(!_tableHearView)
    {
        _tableHearView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.view.width, 86)];
        _tableHearView.backgroundColor = BACKGROUNDCOLOR;//BACKGROUNDCOLOR;
        
        ICSearchButton *searchButton = [[ICSearchButton alloc] initWithFrame:CGRectMake(10, 8, App_Frame_Width - 20, 28)];
        searchButton.layer.cornerRadius = 5;
        [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
        searchButton.layer.backgroundColor = [UIColor whiteColor].CGColor;
        [searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
        [_tableHearView addSubview:searchButton];
    }
    return _tableHearView;
}

- (void)searchAction:(UIButton *)sender {
    ICMessageForwardSearchController *vc = [[ICMessageForwardSearchController alloc] init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UIScrollView *)hearScrollView
{
    if(!_hearScrollView)
    {
        _hearScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 36, self.view.width-10, 50)];
        [self.tableHearView addSubview:_hearScrollView];
        _hearScrollView.backgroundColor = BACKGROUNDCOLOR;
        _hearScrollView.hidden = YES;
    }
    return _hearScrollView;
}

- (NSMutableArray *)selectedArr {
    if (!_selectedArr) {
        _selectedArr = [[NSMutableArray alloc]init];
    }
    return _selectedArr;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (NSMutableArray *)recordgIdList {
    if (!_recordgIdList) {
        _recordgIdList = [[NSMutableArray alloc] init];
    }
    return _recordgIdList;
}

@end
